<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box1 {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
      }
      #box2 {
        width: 100px;
        height: 100px;
        background-color: yellow;
        position: absolute;
        left: 0;
        top: 150px;
      }
    </style>
    <script>
      window.onload = function () {
        var box1 = document.getElementById("box1");
        var btn01 = document.getElementById("btn01");
        var btn02 = document.getElementById("btn02");
        var btn03 = document.getElementById("btn03");
        var btn04 = document.getElementById("btn04");

        btn01.onclick = function () {
          move(box1, "left", 800, 20);
        };

        btn02.onclick = function () {
          move(box1, "left", 0, 10);
        };
        btn03.onclick = function () {
          move(box2, "left", 800, 10);
        };
        btn04.onclick = function () {
          move(box2, "width", 800, 10, function () {
            move(box2, "height", 400, 10, function () {});
          });
        };
        /**
         * 目前定时器的标识由全局变量timer保存
         * 所有的执行的定时器都在这个变量中保存
         */
        // 创建一个可以执行简单函数的函数
        /**
         * obj:要执行的函数
         * attr：要执行动画的样式,比如left top width height
         * target：执行动画的目标位置
         * speed：移动速度
         * callback):回调函数，这个函数将在动画执行完毕
         */
        var timer;
        function move(obj, attr, target, speed, callback) {
          clearInterval(obj.timer);
          var current = parseInt(getStyle(obj, attr));
          if (current > target) {
            speed = -speed;
          }
          obj.timer = setInterval(function () {
            var oldValue = parseInt(getStyle(obj, attr));
            var newValue = oldValue + speed;
            if (
              (speed < 0 && newValue < target) ||
              (speed > 0 && newValue > target)
            ) {
              newValue = target;
            }
            obj.style[attr] = newValue + "px";
            if (newValue == target) {
              clearInterval(obj.timer);
              // 动画执行完毕，调用回调函数
              callback && callback();
            }
          }, 30);
        }
        function getStyle(obj, name) {
          if (window.getComputedStyle) {
            return getComputedStyle(obj, null)[name];
          }
        }
      };
    </script>
  </head>
  <body>
    <button id="btn01">点击按钮后b0x1向右移动</button>
    <button id="btn02">点击按钮后b0x1向左移动</button>
    <button id="btn03">点击按钮后b0x2向右移动</button>
    <button id="btn04">点击按钮</button>
    <div id="box1"></div>
    <div id="box2"></div>
  </body>
</html>
